<template>
  <div class="ai-chat-page">
    <div class="chat-container">
      <!-- 左侧对话列表 -->
      <div class="chat-list">
        <div class="list-header">
          <h3>对话列表</h3>
          <el-button type="primary" @click="createNewChat">
            <el-icon><Plus /></el-icon>
            新建对话
          </el-button>
        </div>
        <div class="list-content">
          <div v-for="(chat, index) in chatList" 
               :key="index"
               :class="['chat-item', { active: currentChatIndex === index }]"
               @click="switchChat(index)">
            <el-icon><ChatDotRound /></el-icon>
            <span class="chat-title">{{ chat.title || '新对话' }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧对话内容 -->
      <div class="chat-main">
        <div class="chat-header">
          <div class="header-left">
            <h2>AI助手</h2>
            <el-tag type="success" effect="plain">在线</el-tag>
          </div>
          <div class="header-right">
            <el-button 
              type="primary" 
              @click="generateVideo" 
              :loading="generating"
            >
              生成视频
            </el-button>
            <el-button type="danger" @click="clearCurrentChat" :disabled="!currentChat">
              清空对话
            </el-button>
          </div>
        </div>

        <div class="chat-messages" ref="messagesContainer">
          <div v-for="(message, index) in currentChat?.messages || []" 
               :key="index" 
               :class="['message-item', message.type]">
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            <div class="message-content" :class="{ 'error-message': message.isError }">
              <div class="message-avatar">
                <el-avatar :size="40" :src="message.type === 'user' ? userAvatar : aiAvatar" />
              </div>
              <div class="message-body">
                <div class="message-text">{{ message.content }}</div>
                <div v-if="message.type === 'ai'" class="message-actions">
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="copyMessage(message.content)"
                    :icon="CopyDocument"
                  >
                    复制
                  </el-button>
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="regenerateResponse(index)"
                    :icon="Refresh"
                  >
                    重新生成
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          <div v-if="loading" class="message-item ai">
            <div class="message-content">
              <div class="message-avatar">
                <el-avatar :size="40" :src="aiAvatar" />
              </div>
              <div class="message-body">
                <div class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <!-- 大模型原始响应显示 -->
          <el-collapse v-if="originalModelResponse" class="model-response-collapse">
            <el-collapse-item title="大模型原始响应">
              <pre class="model-response-content">{{ originalModelResponse }}</pre>
            </el-collapse-item>
          </el-collapse>
          
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题或要求...（Ctrl + Enter 发送）"
            :disabled="loading"
            @keyup.enter.ctrl="sendMessage"
          />
          <div class="input-actions">
            <el-button 
              type="primary" 
              @click="sendMessage" 
              :loading="loading"
              :disabled="!userInput.trim()"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  CopyDocument, 
  Refresh, 
  ChatDotRound,
  Plus 
} from '@element-plus/icons-vue'
import { sendMessageToAI, getAIChatHistory, clearAIChatHistory } from '@/api/VideoAI'
import axios from 'axios'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'

const route = useRoute()

// 头像
const userAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
const aiAvatar = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9cpng.png'

// 状态
const chatList = ref([])
const currentChatIndex = ref(0)
const userInput = ref('')
const loading = ref(false)
const messagesContainer = ref(null)
const originalModelResponse = ref('')

// 上下文信息
const context = ref(null)

// 视频生成状态
const generating = ref(false)

// 计算属性
const currentChat = computed(() => chatList.value[currentChatIndex.value])
const canGenerateVideo = computed(() => {
  return context.value && 
         context.value.stage && 
         context.value.subject && 
         context.value.objective?.length > 0 &&
         context.value.duration && 
         context.value.style &&
         currentChat.value?.messages?.length > 0
})

// 格式化时间
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

// 创建新对话
const createNewChat = () => {
  chatList.value.push({
    title: '新对话',
    messages: [],
    timestamp: new Date().toISOString()
  })
  currentChatIndex.value = chatList.value.length - 1
  userInput.value = ''
}

// 切换对话
const switchChat = (index) => {
  currentChatIndex.value = index
  userInput.value = ''
}

// 清空当前对话
const clearCurrentChat = async () => {
  if (!currentChat.value) return
  
  try {
    await clearAIChatHistory()
    currentChat.value.messages = []
    ElMessage.success('对话已清空')
  } catch (error) {
    ElMessage.error('清空对话失败')
  }
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return
  
  const message = userInput.value.trim()
  userInput.value = ''
  
  // 确保当前对话存在
  if (!currentChat.value) {
    createNewChat()
  }
  
  // 添加用户消息
  currentChat.value.messages.push({
    type: 'user',
    content: message,
    timestamp: new Date().toISOString()
  })
  
  // 更新对话标题（如果是第一条消息）
  if (currentChat.value.messages.length === 1) {
    currentChat.value.title = message.slice(0, 20) + (message.length > 20 ? '...' : '')
  }
  
  // 立即滚动到底部
  await scrollToBottom()
  
  loading.value = true
  
  try {
    const response = await sendMessageToAI({
      message,
      chatId: currentChat.value.id
    })
    
    // 保存原始响应
    if (response.data.originalResponse) {
      originalModelResponse.value = response.data.originalResponse
    } else {
      originalModelResponse.value = JSON.stringify(response.data, null, 2)
    }
    
    // 添加AI回复
    currentChat.value.messages.push({
      type: 'ai',
      content: response.data.reply,
      timestamp: new Date().toISOString()
    })
    
    await scrollToBottom()
  } catch (error) {
    // 添加错误提示消息
    currentChat.value.messages.push({
      type: 'ai',
      content: '抱歉，AI助手暂时无法回应，请稍后再试。',
      timestamp: new Date().toISOString(),
      isError: true
    })
    
    ElMessage.error(error.response?.data?.message || '发送消息失败')
    await scrollToBottom()
  } finally {
    loading.value = false
  }
}

// 重新生成AI回复
const regenerateResponse = async (index) => {
  if (loading.value || !currentChat.value) return
  
  const previousMessages = currentChat.value.messages.slice(0, index + 1)
  const lastUserMessage = previousMessages.findLast(msg => msg.type === 'user')
  
  if (!lastUserMessage) return
  
  loading.value = true
  
  try {
    const response = await sendMessageToAI({
      message: lastUserMessage.content,
      chatId: currentChat.value.id,
      regenerate: true
    })
    
    // 更新AI回复
    currentChat.value.messages[index] = {
      type: 'ai',
      content: response.data.reply,
      timestamp: new Date().toISOString()
    }
    
    await scrollToBottom()
  } catch (error) {
    // 更新为错误提示消息
    currentChat.value.messages[index] = {
      type: 'ai',
      content: '抱歉，重新生成失败，请稍后再试。',
      timestamp: new Date().toISOString(),
      isError: true
    }
    
    ElMessage.error(error.response?.data?.message || '重新生成回复失败')
    await scrollToBottom()
  } finally {
    loading.value = false
  }
}

// 复制消息内容
const copyMessage = async (content) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('复制成功')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 加载对话历史
const loadChatHistory = async () => {
  try {
    const response = await getAIChatHistory()
    chatList.value = response.data
    if (chatList.value.length === 0) {
      createNewChat()
    }
    await scrollToBottom()
  } catch (error) {
    ElMessage.error('加载对话历史失败')
    createNewChat()
  }
}

// 检查配置是否完整
const checkConfig = () => {
  if (!context.value) {
    ElMessage.warning('请先完成视频生成配置')
    return false
  }
  if (!context.value.stage) {
    ElMessage.warning('请选择教学阶段')
    return false
  }
  if (!context.value.subject) {
    ElMessage.warning('请选择教学科目')
    return false
  }
  if (!context.value.objective?.length) {
    ElMessage.warning('请选择教学目标')
    return false
  }
  if (!context.value.duration) {
    ElMessage.warning('请选择视频时长')
    return false
  }
  if (!context.value.style) {
    ElMessage.warning('请选择视频风格')
    return false
  }
  if (!currentChat.value?.messages?.length) {
    ElMessage.warning('请先与AI助手进行对话')
    return false
  }
  return true
}

// 生成视频
const generateVideo = async () => {
  if (!checkConfig()) {
    return
  }
  
  generating.value = true
  try {
    const response = await axios.post('/api/video/generate', {
      ...context.value,
      chatHistory: currentChat.value.messages
    })
    
    ElMessage.success('视频生成成功')
    // 这里可以添加视频预览或下载的逻辑
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '视频生成失败')
  } finally {
    generating.value = false
  }
}

// 初始化上下文信息
const initContext = () => {
  try {
    const contextStr = route.query.context
    if (contextStr) {
      context.value = JSON.parse(contextStr)
    }
  } catch (error) {
    console.error('解析上下文信息失败:', error)
  }
}

onMounted(() => {
  initContext()
  loadChatHistory()
})
</script>

<style scoped>
.ai-chat-page {
  height: 100vh;
  padding: 20px;
  background: #f5f7fa;
}

.chat-container {
  height: 100%;
  display: flex;
  gap: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-list {
  width: 250px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.list-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.list-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.chat-item {
  padding: 12px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  transition: all 0.3s;
}

.chat-item:hover {
  background: #f5f7fa;
}

.chat-item.active {
  background: #ecf5ff;
  color: #1a73e8;
}

.chat-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}

.message-item {
  margin-bottom: 20px;
}

.message-time {
  text-align: center;
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.message-content {
  display: flex;
  gap: 12px;
  max-width: 80%;
  margin: 0 auto;
}

.message-item.user .message-content {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-body {
  flex: 1;
  background: #fff;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  word-break: break-word;
}

.message-item.user .message-body {
  background: #1a73e8;
  color: #fff;
}

.message-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.loading-dots {
  display: flex;
  gap: 4px;
  padding: 4px 0;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  background: #909399;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background: #fff;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.error-message .message-body {
  background: #fef0f0;
  color: #f56c6c;
}

.message-body:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.model-response-collapse {
  margin-bottom: 15px;
  border-radius: 4px;
  overflow: hidden;
}

.model-response-content {
  font-family: monospace;
  font-size: 13px;
  white-space: pre-wrap;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

/* 加载动画 */
</style> 